﻿using System.Collections;
using UnityEngine;
using YooAsset;

namespace LFrameworkAOT 
{
    internal class FsmRequestPackageVersion : IStateNode
    {
        private StateMachine m_Machine;
        PatchOperation m_PatchOperation;

        void IStateNode.OnCreate(StateMachine machine)
        {
            m_Machine = machine;
            m_PatchOperation = m_Machine.Owner as PatchOperation;
        }
        void IStateNode.OnEnter()
        {
            m_PatchOperation.StartRequestVersion();
            GameLaunch.Instance.StartCoroutine(UpdatePackageVersion());
        }
        void IStateNode.OnUpdate()
        {
        }
        void IStateNode.OnExit()
        {
        }

        private IEnumerator UpdatePackageVersion()
        {
            var packageName = (string)m_Machine.GetBlackboardValue("PackageName");
            var package = YooAssets.GetPackage(packageName);
            var operation = package.RequestPackageVersionAsync();
            yield return operation;

            if (operation.Status != EOperationStatus.Succeed)
            {
                Debug.LogWarning(operation.Error);
                m_PatchOperation.RequestVersionFailed();
            }
            else
            {
                Debug.Log($"Request package version : {operation.PackageVersion}");
                m_Machine.SetBlackboardValue("PackageVersion", operation.PackageVersion);
                m_Machine.ChangeState<FsmUpdatePackageManifest>();
            }
        }
    }
}
